package encaps.utils.rendering;

import encaps.resources.Response;
import encaps.utils.html.HTMLElement;
import encaps.utils.html.HTMLElementSequence;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Element;

public class Renderer {

    private static final Map<String, Parser> parsers;

    static {
        parsers = new HashMap<String, Parser>();
        Parser entityParser = new EntityParser();
        parsers.put(Response.ENTITY, entityParser);
        Parser textMessageParser = new TextMessageParser();
        parsers.put(Response.TEXT_MESSAGE, textMessageParser);
        Parser tableParser = new TableParser();
        parsers.put(Response.TABLE, tableParser);
    }

    public static String renderResult(Element resultXML) {

        if (resultXML == null) {
            return "";
        }
        //System.out.println("res:\n"+encaps.utils.XMLHelper.toString(resultXML));

        List children = resultXML.getChildren();
        if (children.isEmpty()) {
            return "";
        }
        boolean first = true;
        HTMLElementSequence result = new HTMLElementSequence();
        for (Object obj : children) {
            if (!first) {
                result.addContent(HTMLElement.createBr());
                result.addContent(HTMLElement.createBr());
            }
            first = false;
            Element child = (Element) obj;
            String responseType = child.getName();
            Parser parser = parsers.get(responseType);
            result.addContent(parser.renderToHTML(resultXML));
        }
        return result.toString();

    }
}
